# -*- coding:utf-8 -*-
# @Time     :2024/3/14 22:37
# @Author   :CHNJX
# @File     :checker.py
# @Desc     :
from datetime import datetime, timedelta
from excel_handler import ExcelHandler
from log_analyzer import LogAnalyzer
from performance_result_processor import PerformanceResultProcessor


class DailyChecker:
    def __init__(self, log_path, performance_data_path, excel_path):
        self.log_path = log_path
        self.performance_data_path = performance_data_path
        self.excel_path = excel_path
        self.log_analyzer = LogAnalyzer(log_path)
        self.performance_result_processor = PerformanceResultProcessor(performance_data_path)
        self.excel_handler = ExcelHandler(excel_path)

    def execute_daily_checks(self, before_date: int = 1):
        # 获取日志分析结果
        log_data = self.log_analyzer.analyze_all_logs(before_date)

        # 获取性能结果
        performance_data = self.performance_result_processor.process_performance_results()

        # 合并数据
        merged_data = self.merge_data(log_data, performance_data)

        # 记录到Excel
        self.record_data_to_excel(merged_data, before_date)

    def merge_data(self, log_data, performance_data):
        """合并日志和性能数据"""
        merged_data = {}
        # 处理日志数据
        for key, value in log_data.items():
            if isinstance(value, tuple):
                # 将元组转换为字典格式
                merged_data[key] = {
                    '昨日日志': (value[0], value[2]),  # (状态, 错误列表)
                    '硬盘信息': (value[1], value[3])   # (状态, 错误列表)
                }
            else:
                merged_data[key] = value
                
        # 处理性能数据
        for key, value in performance_data.items():
            if key in merged_data:
                merged_data[key].update(value)
            else:
                merged_data[key] = value
        return merged_data

    def record_data_to_excel(self, data, before_date: int = 1):
        """将合并的数据记录到Excel中"""
        date_str = (datetime.now() - timedelta(days=before_date)).strftime("%m%d")
        sheet_name = f"拷机日报-{date_str}"
        
        # 先进行复制
        if not self.excel_handler.copy_template_sheet('template', sheet_name):
            print(f"无法从模板创建新的表格 {sheet_name}，请确保模板表格存在")
            return
        
        new_sheet = self.excel_handler.workbook[sheet_name]
        
        # 定义一个辅助函数来清理字符串
        def clean_string(s):
            if not isinstance(s, str):
                return str(s) if s is not None else ""
            
            # 移除Excel不允许的字符
            cleaned = ""
            for c in s:
                # 过滤ASCII值为0-31的控制字符(除了\t, \n, \r)
                if ord(c) < 32 and c not in '\t\n\r':
                    continue
                # 还有一些其他可能导致问题的字符
                if c in '\x7f\ufeff\u2028\u2029':
                    continue
                cleaned += c
            return cleaned
        
        for model, updates in data.items():
            for row in new_sheet.iter_rows(min_row=2, max_col=8):
                if row[0].value == model:  # 假设型号在第一列
                    for cell in row:
                        if cell.value in updates:
                            current_row = cell.row
                            col_num = cell.column
                            while True:
                                cur_cell = new_sheet[current_row][col_num - 1]
                                if cur_cell.value in updates:
                                    update_col = col_num + 2  # 本次数据列
                                    error_col = col_num + 3  # 错误信息列
                                    
                                    # 处理数据
                                    if cur_cell.value in ['昨日日志', '硬盘信息']:
                                        if cur_cell.value in updates:
                                            status, errors = updates[cur_cell.value]
                                            
                                            # 清理状态值
                                            status_clean = clean_string(status)
                                            new_sheet.cell(row=cur_cell.row, column=update_col).value = status_clean
                                            
                                            # 清理每个错误信息，然后再连接
                                            if errors:
                                                cleaned_errors = [clean_string(err) for err in errors]
                                                # 过滤掉空字符串
                                                cleaned_errors = [err for err in cleaned_errors if err]
                                                error_text = '\n'.join(cleaned_errors) if cleaned_errors else ""
                                                new_sheet.cell(row=cur_cell.row, column=error_col).value = error_text
                                            else:
                                                new_sheet.cell(row=cur_cell.row, column=error_col).value = ""
                                    else:
                                        # 如果是性能数据，也清理后再写入
                                        value = updates.get(cur_cell.value)
                                        value_clean = clean_string(value)
                                        new_sheet.cell(row=cur_cell.row, column=update_col).value = value_clean
                                
                                if cur_cell.value == '昨日日志':
                                    break
                                current_row += 1
                            break
        
        try:
            self.excel_handler.workbook.save(self.excel_path)
            print(f"成功保存到: {self.excel_path}")
        except Exception as e:
            print(f"保存时出错: {type(e).__name__}: {e}")